package com.order.services.impl;

import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.order.Order;
import com.example.product.Product;
import com.order.openfeign.ProductOpenfeignClient;
import com.order.services.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    DiscoveryClient discoveryClient;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    LoadBalancerClient loadBalancerClient;

    @Autowired
    ProductOpenfeignClient productOpenfeignClient;

    // 第二种 流量控制异常处理方式。 适用对自定义资源的流量控制
    @SentinelResource(value = "createOrder", blockHandler = "createOrderBlockHandler")
    @Override
    public Order createOrder(Long productId, Long userId) {
//        Product product = getProductFromRemoteLoadBalancedAnno(productId);
        // 第三种 流量控制异常处理方式。 使用openFeign的兜底返回 fallback
        Product product = productOpenfeignClient.getProductById(productId);
        Order order = new Order();
        order.setId(1L);
        order.setTotalPrice(product.getPrice().multiply(new BigDecimal(product.getNum())));
        order.setUserId(userId);
        order.setNickName("zhang di");
        order.setAddress("沈阳");
        order.setProductList(List.of(product));

        // 第四种 流量控制异常处理方式。 硬编码方式 套娃
//        try {
//            SphU.entry("servicesName");
//        } catch (BlockException e) {
//            throw new RuntimeException(e);
//        }
        return order;
    }

    public Order createOrderBlockHandler(Long productId, Long userId, BlockException e) {
        Order order = new Order();
        order.setId(0L);
        order.setUserId(userId);
        order.setNickName("未知： 异常");
        return order;
    }

    // 使用 loadBalancerClient 完成负载均衡
    private Product getProductFromRemoteLoadBalancedAnno(Long productId) {
        String uri =  "http://" + "services-product" + "/product/" + productId;
        return restTemplate.getForObject(uri, Product.class);
    }

    // 使用 loadBalancerClient 完成负载均衡
    private Product getProductFromRemoteLoadBalanced(Long productId) {
        ServiceInstance instance = loadBalancerClient.choose("services-product");
        System.out.println("target Product port : " + instance.getPort());
        String uri =  "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + productId;
        return restTemplate.getForObject(uri, Product.class);
    }
    private Product getProductFromRemote(Long productId) {

        List<ServiceInstance> instances = discoveryClient.getInstances("services-product");
        ServiceInstance instance = instances.get(0);
        String uri =  "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + productId;
        return restTemplate.getForObject(uri, Product.class);
    }
}
